package biz

import (
	"context"
	"errors"

	"github.com/go-kratos/kratos/v2/log"
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	ID           int64
	Username     string
	PasswordHash string
	Status       int32
	CreatedAt    string
	UpdatedAt    string
}

type UserRepo interface {
	CreateUser(ctx context.Context, user *User) (*User, error)
	GetUser(ctx context.Context, id uint) (*User, error)
	GetUserByUsername(ctx context.Context, username string) (*User, error)
}

type UserUseCase struct {
	repo UserRepo
	log  *log.Helper
}

func NewUserUseCase(repo UserRepo, logger log.Logger) *UserUseCase {
	return &UserUseCase{
		repo: repo,
		log:  log.NewHelper(log.With(logger, "module", "biz/user")),
	}
}

func (uc *UserUseCase) CreateUser(ctx context.Context, username, password string) (*User, error) {
	// 密码加密

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return nil, err
	}
	uc.log.Infof("-----username: %s, password: %s", username, password)
	user := &User{
		Username:     username,
		PasswordHash: string(hashedPassword),
		Status:       1, // 默认激活状态
	}

	return uc.repo.CreateUser(ctx, user)
}

func (uc *UserUseCase) GetUser(ctx context.Context, id uint) (*User, error) {
	return uc.repo.GetUser(ctx, id)
}

func (uc *UserUseCase) VerifyPassword(ctx context.Context, username, password string) (bool, int64, error) {
	user, err := uc.repo.GetUserByUsername(ctx, username)
	if err != nil {
		return false, 0, err
	}

	if user.Status != 1 {
		return false, 0, errors.New("user is disabled")
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
	if err != nil {
		return false, 0, nil
	}

	return true, user.ID, nil
}
